package com.csc.service.impl;

import com.csc.entity.Allocation;
import com.csc.entity.Dormitory;
import com.csc.mapper.AllocationMapper;
import com.csc.mapper.DormitoryMapper;
import com.csc.service.DormitoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class DormitoryServiceImpl implements DormitoryService {

    @Autowired
    private DormitoryMapper dormitoryMapper;
    @Autowired
    private AllocationMapper allocationMapper;

    @Override
    public List<Dormitory> findAll() {
        return dormitoryMapper.findAll();
    }

    @Override
    public List<Dormitory> findAvailable() {
        return dormitoryMapper.findAvailable();
    }

    @Override
    public Dormitory findById(Long id) {
        return dormitoryMapper.findById(id);
    }

    @Override
    public void save(Dormitory dormitory) {
        if(dormitory.getId()  == null) {
            dormitoryMapper.insert(dormitory);
        } else {
            dormitoryMapper.update(dormitory);
        }
    }

    @Override
    public void delete(Long id) {
        List<Allocation> allocations = allocationMapper.findByDormitoryId(id);
        if(!allocations.isEmpty())  {
            throw new RuntimeException("该宿舍仍有学生居住，无法删除");
        }
        dormitoryMapper.delete(id);
    }
}